var app = getApp()
var bmap = require('../../../utils/bmap-wx.min.js');
let WebIM = require("../../../utils/webim")["default"];
let __test_account__, __test_psword__;
let disp = require("../../../utils/broadcast");
let runAnimation = true
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hint:true,
    name: "",
    psd: "123",
    grant_type: "password",
    colorArr: ["#f8b551", "#ea68a2", "#80c269", "#00b7ee"],
    bigMask: false,
    noticelunbo:[
      { names: "张三", doctorname: "李浩", times: "1" },
      { names: "王五", doctorname: "李浩", times: "1" },
      {names:"李四",doctorname:"李浩",times:"1"},
    ]
  },
  // 医生说更多
  doctrospeack: function () {
    wx.navigateTo({
      url: '/hyb_yl/userLife/pages/doctrospeack/doctrospeack',
    })
  },
  // 医说详情
  speackdetail: function (e) {
    console.log(e)
    var index = e.detail
    wx.navigateTo({
      url: '/hyb_yl/userLife/pages/zixunanlixq/zixunanlixq',
    })
  },
  searchbtn(){
    wx.navigateTo({
      url: '/hyb_yl/mysubpages/pages/search/search',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var me = this
    this.getBase()
    me.loadInfo();
    var baidukey = wx.getStorageSync('baidukey')
    var BMap = new bmap.BMapWX({
      ak: baidukey
    });
    if (wx.getStorageSync('openid') !== "") {
      app.util.request({
        url: "entry/wxapp/Authorize.ifregister",
        data: {
          openid: wx.getStorageSync('openid')
        },
        success: function (resing) {
          console.log(resing)
          var myUsername = resing.data
          if (resing.data !== "") {
            wx.setStorage({
              key: "myUsername",
              data: resing.data
            });
            new app.ToastPannel.ToastPannel();
            disp.on("em.xmpp.error.passwordErr", function () {
              me.toastFilled('用户名或密码错误');
            });
            me.login(myUsername);
          }
        }
      })
      var city = wx.getStorageSync('city')
      me.setData({
        position:city
      })
    }
    //记录登记时间（每天记录一次）
    app.util.request({
      url: "entry/wxapp/Authorize.logintime",
      data: {
        openid: wx.getStorageSync('openid')
      },
      success: function (res) {
        console.log(res)
      }
    })
    setTimeout(function(){
      me.setData({
        hint:false
      })
    },3000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
    this.getMenu()
    this.getServer()
    this.getLmhosp()
    this.getFenlei()
    this.getTeserver()
    this.getYishuo()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var me = this
    if (wx.getStorageSync('openid') !== "") {
      app.util.request({
        url: "entry/wxapp/Authorize.ifregister",
        data: {
          openid: wx.getStorageSync('openid')
        },
        success: function (resing) {
          console.log(resing)
          var myUsername = resing.data
          if (resing.data !== "") {
            wx.setStorage({
              key: "myUsername",
              data: resing.data
            });
            new app.ToastPannel.ToastPannel();
            disp.on("em.xmpp.error.passwordErr", function () {
              me.toastFilled('用户名或密码错误');
            });
            me.login(myUsername);
          }
        }
      })
    }
    var city = wx.getStorageSync('city')
    me.setData({
      position:city
    })
    var openid = wx.getStorageSync('openid')
    console.log(openid)
    if (openid) {
      me.setData({
        bigMask: true
      })
    } else {
      me.setData({
        bigMask: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getBase()
    this.getMenu()
    this.getServer()
    this.getLmhosp()
    this.getFenlei()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //基础设置
  getBase: function () {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.base',
      success: function (res) {
        console.log(res)
        var se = res.data.ztcolor
        console.log(se)
        var baidukey = res.data.baidukey
        se = "#0088de"
        wx.setStorageSync('baidukey', baidukey)
        that.setData({
          baseinfo: res.data,
          se: se
        })
        wx.setNavigationBarTitle({
          title: res.data.show_title
        })
        wx.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: se,
        })
        wx.setStorage({
          key: 'color',
          data: se,
        })
      },
      fail: function (err) {
        console.log(err)
      },
    })
  },
  //菜单
  getMenu() {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.menu',
      success: function (res) {
        let menuArr = res.data.arr
        let Length = menuArr.length;
        that.setData({
          ['menuArr[' + Length + ']']: res.data.arr,
        })
        console.log(that.data.menuArr)
      }
    })
  },
  //wenzhen服务
  getServer() {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.server',
      success: function (res) {
        console.log(res)
        let serArr = res.data
        let Length = serArr.length;
        var backArr = ['#ebeffa', '#ebfaf1', '#faf6eb', '#faebfa', '#ebf9fa', '#f7faeb']
        var index = 0;
        for (var i = 0; i < serArr.length; i++) {
          var serArr1 = serArr[i].background = backArr[index]
          index++
          if (backArr[index] == undefined) {
            index = 0
          }
        }
        that.setData({
          ['serArr[' + Length + ']']: res.data,
        })
        console.log(serArr)
      }
    })
  },
  //特色服务
  getTeserver() {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.teserver',
      success: function (res) {
        console.log(res)
        let teserver = res.data
        let Length = teserver.length;
        var index = 0;
        for (var i = 0; i < teserver.length; i++) {

          if (teserver[i].pinyin == 'shoushukuaiyue') {
            var teserver1 = teserver[i].button = '立即预约'
          }
          if (teserver[i].pinyin == 'tijianjiedu') {
            var teserver1 = teserver[i].button = '立即解读'
          }
          if (teserver[i].pinyin == 'zhuanjiatuandui') {
            var teserver1 = teserver[i].button = '签约医生'
          }
          if (teserver[i].pinyin == 'zaixianguahao') {
            var teserver1 = teserver[i].button = '立即挂号'
          }
        }
        that.setData({
          ['teserver[' + Length + ']']: res.data,
        })
        console.log(teserver)
      }
    })
  },
  //联盟医院
  getLmhosp() {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.cooperative_hospital',
      success: function (res) {
        console.log(res)
        let hospitaArr = res.data
        let Length = hospitaArr.length;
        that.setData({
          ['hospitaArr[' + Length + ']']: res.data,
        })
      }
    })
  },
  //合作医院详情
  hzyyxq(e) {
    var that = this
    var title = e.currentTarget.dataset.title
    var hid = e.currentTarget.dataset.id
    var uid = e.currentTarget.dataset.uid
    wx.navigateTo({
      url: '/hyb_yl/userLife/pages/specialtyContent/specialtyContent?hid=' + hid + '&title=' + title + '&uid=' + uid,
    })
  },
  //专病服务
  getFenlei() {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.zixunfenlei',
      success: function (res) {
        console.log("-----------------")
        console.log(res)
        let fenleiArr = res.data
        let Length = fenleiArr.length;
        that.setData({
          ['fenleiArr[' + Length + ']']: res.data,
        })
      }
    })
  },
  //按钮跳转
  buttonsite(e) {
    console.log(e)
    var that = this
    var title = e.detail.value.title
    var link = e.detail.value.link
    var form_id = e.detail.formId
    app.util.request({
      'url': 'entry/wxapp/Index.userformId',
      data: {
        form_id: form_id,
        openid: wx.getStorageSync('openid')
      },
      success: function (res) {
        console.log(res)
      }
    })
    if (title == "Svip"){
      wx.navigateTo({
        url: '/hyb_yl/backstageServices/pages/vip/vip',
      })
    } else {
      wx.navigateTo({
        url: link + '?title=' + title,
      })
    }
  },
  wenzhen(e) {
    var sid = e.detail.value.sid
    var pinyin = e.detail.value.pinyin
    var name = e.detail.value.name
    if (pinyin == 'yuanchengwenzhen') {
      wx.navigateTo({
        url: '/hyb_yl/czhuanjiasubpages/pages/longsever/index?sid=' + sid + '&key=' + pinyin + '&name=' + name,
      })
    } else if (pinyin == "kuaisuwenzhen") {
      wx.navigateTo({
        url: '/hyb_yl/userLife/pages/index/index',
      })
    } else {
      wx.navigateTo({
        url: '/hyb_yl/userCommunicate/pages/changeDoctor/changeDoctor?sid=' + sid + '&key=' + pinyin + '&name=' + name,
      })
    }

  },
  //点击专病服务下的按钮
  zbfw(e) {
    var zx_id = e.detail.value.zx_id;
    var index = e.detail.value.index
    console.log(e)
    wx.reLaunch({
      url: '/hyb_yl/tabBar/jibingyufang/jibingyufang?zx_id=' + zx_id + '&index=' + index
    })
  },
  //体检解读
  tijianjiedu(e) {
    console.log(e)
    var that = this
    var pinyin = e.currentTarget.dataset.key
    var name = e.currentTarget.dataset.name
    var sid = e.currentTarget.dataset.sid
    wx.navigateTo({
      url: '/hyb_yl/userCommunicate/pages/changeDoctor/changeDoctor?sid=' + sid + '&key=' + pinyin + '&name=' + name,
    })
  },
  //手术预约
  shoushukuaiyue(e) {
    var that = this
    var pinyin = e.currentTarget.dataset.key
    var name = e.currentTarget.dataset.name
    var sid = e.currentTarget.dataset.sid
    wx.navigateTo({
      url: '/hyb_yl/userCommunicate/pages/changeDoctor/changeDoctor?sid=' + sid + '&key=' + pinyin + '&name=' + name,
    })
  },
  //家庭医生
  sirenyisheng(e) {
    var that = this
    var pinyin = e.currentTarget.dataset.key
    var name = e.currentTarget.dataset.name
    var sid = e.currentTarget.dataset.sid
    wx.navigateTo({
      url: '/hyb_yl/userCommunicate/pages/changeDoctor/changeDoctor?sid=' + sid + '&key=' + pinyin + '&name=' + name
    })
  },
  loadInfo: function () {
    var that = this
    wx.getLocation({
      type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标  
      success: function (res) {
        console.log(res)
        var longitude = res.longitude
        var latitude = res.latitude
        that.loadCity(longitude, latitude)
      },
      
      fail: function () {
        // fail  
      },
      complete: function () {
        // complete  
      }
    })
  },

  distance: function (la1, lo1, la2, lo2) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137; //地球半径
    s = Math.round(s * 10000) / 10000;
    this.setData({
      s: s
    })
  },
  loadCity: function (longitude, latitude) {
    var page = this
    var baidukey = wx.getStorageSync('baidukey')
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/?ak=' + baidukey + '&location=' + latitude + ',' + longitude + '&output=json',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        if (res.data.message) {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        } else {
          var city = res.data.result.addressComponent.city;
          wx.setStorageSync('city', city)
          //查询当前城市的所有活动
          var lat = res.data.result.location.lat
          var lng = res.data.result.location.lng
          var sematic_description = res.data.result.sematic_description
          var types = 0
          page.setData({
            position: city,
            lat: lat,
            lng: lng,
            sematic_description: sematic_description
          });
        }
      },
      fail: function () {},
      complete: function () {}
    })
  },
  hotmore() {
    wx.navigateTo({
      url: '/hyb_yl/twosubpages/pages/publicProblems/publicProblems',
    })
  },
  zhuanbingfuwu() {
    wx.reLaunch({
      url: '/hyb_yl/tabBar/jibingyufang/jibingyufang',
    })
  },
  hotdetail(){
    wx.navigateTo({
      url: '/hyb_yl/twosubpages/pages/publicProblemsInfor/publicProblemsInfor',
    })
  },
  bindUsername: function (e) {
    this.setData({
      name: e.detail.value
    });
  },

  bindPassword: function (e) {
    this.setData({
      psd: e.detail.value
    });
  },
  onFocusPsd: function () {
    this.setData({
      psdFocus: 'psdFocus'
    })
  },
  onBlurPsd: function () {
    this.setData({
      psdFocus: ''
    })
  },
  onFocusName: function () {
    this.setData({
      nameFocus: 'nameFocus'
    })
  },
  onBlurName: function () {
    this.setData({
      nameFocus: ''
    })
  },

  login: function () {
    runAnimation = !runAnimation
    wx.setStorage({
      key: "myUsername",
      data: wx.getStorageSync('myUsername')
    });

    getApp().conn.open({
      apiUrl: WebIM.config.apiURL,
      user: wx.getStorageSync('myUsername'),
      pwd: '123',
      grant_type: this.data.grant_type,
      appKey: WebIM.config.appkey
    });

  },
  zhuanjiatuandui(e) {
    var that = this
    var pinyin = e.currentTarget.dataset.key
    var name = e.currentTarget.dataset.name
    var sid = e.currentTarget.dataset.sid
    wx.navigateTo({
      url: '/hyb_yl/doctor/pages/familydoctor/mydoctor/mydoctor?sid=' + sid + '&key=' + pinyin + '&name=' + name,
    })
  },
  zaixianguahao(e){
    var pinyin = e.currentTarget.dataset.key
    var name = e.currentTarget.dataset.name
    var sid = e.currentTarget.dataset.sid
    wx.navigateTo({
      url: '/hyb_yl/czhuanjiasubpages/pages/longsever/index?sid=' + sid + '&key=' + pinyin + '&name=' + name,
    })
  },
  //查询当前用户是否有签约家庭医生
  getYishuo() {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/Index.userqydoc',
      data: {
        openid: wx.getStorageSync('openid')
      },
      success: function (result) {
        console.log(result)
        that.setData({
          doctorspeack:result.data
        })
      }
    })
  }
})